import MusicList from '@/components/music-list/music-list'
import storage from 'good-storage'
import { processSongs } from '@/service/song'

export default function createDetailComponent (name, key, fetch) {
  return {
    name,
    components: {
      MusicList
    },
    props: {
      data: {
        type: Object,
        default: null
      }
    },
    data () {
      return {
        songs: []
      }
    },
    computed: {
      computedData () {
        let ret = null
        const data = this.data
        if (data) {
          ret = data
        } else {
          const cachedData = storage.get(key)
          // console.log(cachedSinger)
          if (cachedData && (cachedData.mid || cachedData.id + '') === this.$route.params.id) {
            ret = cachedData
          }
        }
        return ret
      },
      pic () {
        const data = this.computedData
        return data && data.pic
      },
      title () {
        const data = this.computedData
        return data && (data.name || data.title)
      }
    },
    async created () {
      // 如果用户自行修改了ulr的id，导致computedData为null，则返回上级
      if (!this.computedData) {
        const path = this.$route.matched[0].path
        this.$router.push({ path })
      } else {
        const data = this.computedData
        const result = await fetch(data)
        this.songs = await processSongs(result.songs)
      }
    }
  }
}
